package cn.qzbook.redisData;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;

/**
 * @Description
 * @Author zc
 * @Date 2020/11/8 上午12:36
 */
public class RedisHash {

    public static void main(String[] args) {
        RedisHash redisHash = new RedisHash();
        redisHash.testHash();
    }

    public void testHash(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:application.xml");

        RedisTemplate template = context.getBean(RedisTemplate.class);

        String key = "hash";

        Map<String,String> map = new HashMap<>();
        map.put("f1","val1");
        map.put("f2","val2");

        //相当于hmset命令
        template.opsForHash().putAll(key,map);

        //相当于hset命令
        template.opsForHash().put(key,"f3","6");
        printValueForHash(template,key,"f3");

        //相当于hexists key filed命令
        boolean exists = template.opsForHash().hasKey(key,"f3");
        System.out.println(exists);

        //相当于hgetall命令
        Map keyValMap = template.opsForHash().entries(key);

        //相当于hincrby命令
        template.opsForHash().increment(key,"f3",2);
        printValueForHash(template,key,"f3");

        //相当于bincrbyfloat命令
        template.opsForHash().increment(key,"f3",0.88);
        printValueForHash(template,key,"f3");

        //相当于hvals命令
        List values = template.opsForHash().values(key);

        //相当于hkeys命令
        Set keys = template.opsForHash().keys(key);

        List<String> fieldList = new ArrayList<>();
        fieldList.add("f1");
        fieldList.add("f2");
        //相当于hmge命令
        template.opsForHash().multiGet(key,keys);

        //相当于hsetnx命令
        boolean success = template.opsForHash().putIfAbsent(key,"f4","val4");
        System.out.println(success);

        //相当于hdel命令
        Long result = template.opsForHash().delete(key,"f1","f2");
        System.out.println(result);


    }

    public static void printValueForHash(RedisTemplate template,String key,String filed){
        System.out.println(template.opsForHash().get(key, filed));
    }



}
